package com.shanzhe.eshop.common.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @Author yinwei
 * @create 2021/12/25
 * @Version 1.0
 */
public class ChannelDemo {

    public static void main(String[] args) throws Exception{
       /* FileOutputStream outputStream = new FileOutputStream("G:\\file\\tmp\\hello.txt");
        FileChannel channel = outputStream.getChannel();*/

       FileInputStream fileInputStream = new FileInputStream("G:\\file\\tmp\\hello.txt");
       FileChannel channel = fileInputStream.getChannel();

        //写
        /*ByteBuffer byteBuffer = ByteBuffer.wrap("hello word".getBytes());
        channel.write(byteBuffer);
        byteBuffer.rewind();
        channel.position(5);
        channel.write(byteBuffer);*/

        //channel.lock(0,Integer.MAX_VALUE,true);
        //读
        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(5);
        channel.write(byteBuffer);
        channel.read(byteBuffer);
        byteBuffer.flip();
        byte[] data = new byte[5];
        byteBuffer.get(data);

        System.out.println(data.length);

        channel.close();
        fileInputStream.close();
    }
}
